package com.learn.authentication.config;

import com.learn.authentication.filters.JwtAuthenticationTokenFilter;
import jakarta.servlet.Filter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.util.ArrayList;
import java.util.List;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/06
 * @description spring security的配置类
 * 新版本使用注解@EnableWebSecurity代替WebSecurityConfigurerAdapter
 *
 * EnableGlobalMethodSecurity(prePostEnabled = true) 是旧版的写法
 * 新版使用EnableMethodSecurity，而且prePostEnabled默认为true
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 直接new一个BCrypt加密器，新版本可以不用继承那个类
     *
     * @return
     */
    @Bean
    public PasswordEncoder getBCrypt() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager getAuthenticationManager() {
        try {
            return authenticationConfiguration.getAuthenticationManager();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 新版本的写法都是用lambda表达式写法，前后端分离时可以需要警用csrf， session
                // 需要禁用才能放行
                .csrf(csrf -> csrf.disable())
                // 完全无状态，不创建/使用 Session
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 添加自定义 JWT 过滤器
                .addFilterBefore(jwtAuthenticationTokenFilter,  // 你的过滤器
                        UsernamePasswordAuthenticationFilter.class  // 插入到哪个过滤器之前
                )
                .authorizeHttpRequests(authorize -> authorize
                        // 匿名访问，未登录（认证）状态下才能访问
                        .requestMatchers("/user/login").anonymous()
                        // 其他的任意请求，都必须认证了再放行
                        .anyRequest().authenticated()
                );
        return http.build();
    }

    /*@Bean
    public SecurityFilterChain securityFilterChainEmpty(HttpSecurity http) throws Exception {
        return new SecurityFilterChain() {
            private RequestMatcher requestMatcher = request -> request
                    .getRequestURI().startsWith("/user/login");
            @Override
            public boolean matches(HttpServletRequest request) {
                return requestMatcher.matches(request);
            }
            @Override
            public List<Filter> getFilters() {
                return new ArrayList<>();
            }
        };
    }*/
}
